/* eslint-disable react-hooks/rules-of-hooks */
import { useContext, useEffect, useRef } from "react"
import { KeepAliveContext } from "./keepAliveContext"


export function KeepAliveTransfer(KeepAliveComponent, keepAliveId) {

    return function(props) {
        const _ref = useRef(null) 
        const { keepAliveStates, setKeepAliveState } = useContext(KeepAliveContext)
        // console.log('keepAliveStates', keepAliveStates);
        // console.log('setKeepAliveState', setKeepAliveState);
        useEffect(() => {
            const state = keepAliveStates[keepAliveId]
    
            if(state && state.nodes) {
                console.log('有节点', state);
                state.nodes.forEach(node => _ref.current.appendChild(node))
            } else {
                console.log('无节点', state);
                setKeepAliveState({
                    reactElement: <KeepAliveComponent { ...props }/>,
                    keepAliveId
                })
            }
        }, [keepAliveStates, setKeepAliveState, props])
        return (
            <div ref={ _ref }></div>
        )
    }
}

